package com.wst.system.util;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class TimeUtils {

    public static void main(String[] args) {
        String dateStr = "2023-03-01 12:00:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
        LocalDateTime now = LocalDateTime.now();

        String relativeTime = getRelativeTime(dateTime, now);
        System.out.println(relativeTime);
    }


    public static String getRelativeTime(String dateStr){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
        LocalDateTime now = LocalDateTime.now();
        String relativeTime = getRelativeTime(dateTime, now);
        return relativeTime;
    }



    public static String getRelativeTime(LocalDateTime past, LocalDateTime now) {
        Duration duration = Duration.between(past, now);

        long seconds = duration.getSeconds();
        if (seconds < 60) {
            return seconds + "秒前";
        }

        long minutes = duration.toMinutes();
        if (minutes < 60) {
            return minutes + "分钟前";
        }

        long hours = duration.toHours();
        if (hours < 24) {
            return hours + "小时前";
        }

        long days = duration.toDays();
        if (days < 30) {
            return days + "天前";
        }

        long months = ChronoUnit.MONTHS.between(past, now);
        if (months < 12) {
            return months + "个月前";
        }

        long years = ChronoUnit.YEARS.between(past, now);
        return years + "年前";
    }

    public static String getRelativeTime(Date date) {
        // 将 Date 转换为 LocalDateTime
        LocalDateTime past = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime now = LocalDateTime.now();

        // 计算时间差
        Duration duration = Duration.between(past, now);

        long seconds = duration.getSeconds();
        if (seconds < 60) {
            return seconds + "秒前";
        }

        long minutes = duration.toMinutes();
        if (minutes < 60) {
            return minutes + "分钟前";
        }

        long hours = duration.toHours();
        if (hours < 24) {
            return hours + "小时前";
        }

        long days = duration.toDays();
        if (days < 30) {
            return days + "天前";
        }

        long months = ChronoUnit.MONTHS.between(past, now);
        if (months < 12) {
            return months + "个月前";
        }

        long years = ChronoUnit.YEARS.between(past, now);
        return years + "年前";
    }
}
